package com.zc.security.service.impl;

import com.zc.security.domain.LoginUser;
import com.zc.security.domain.User;
import com.zc.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 默认security会调用UserDetailsService接口的实现类来验证用户信息，我们只要重写这个类就可以了。
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        User user = userService.lambdaQuery().eq(User::getUserName, username).one();
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 由于UserDetails是个接口，所以需要自己定义个对象来返回

        //查询对应的权限信息
        return new LoginUser(user);
    }
}
